//
//  WHSNetworkParser.m
//  HimalayaFM
//
//  Created by WuHanShuai on 16/4/19.
//  Copyright © 2016年 Wu. All rights reserved.
//

#import "WHSNetworkParser.h"
#import "AFNetworking.h"
@implementation WHSNetworkParser

+ (void)GETWithURL:(NSString *)urlStr
               par:(NSDictionary *)dic
           success:(void (^)(id))responseObj filed:(void (^)(NSError *))err
{
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"%@", documentPath);
    
    // 文件管理器
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *musicCaches = [documentPath stringByAppendingPathComponent:@"musicCaches"];
    BOOL resultFile =  [manager createDirectoryAtPath:musicCaches withIntermediateDirectories:YES attributes:nil error:nil];
    if (resultFile) {
        NSLog(@"创建缓存文件夹成功");
    }
    // 拼接缓存路径
    NSString *path = [NSString stringWithFormat:@"%ld.plist", (unsigned long)[urlStr hash]];
    NSString *textFilePath = [musicCaches stringByAppendingPathComponent:path];
   

    // 检测网络连接的单例,网络变化时回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"网络状态 = %ld", status);
    }];
    
    
    AFHTTPSessionManager *man = [AFHTTPSessionManager manager];
    // 有的返回的数据格式，AFN不支持解析，所以我们要设置一下。让AFN支持。
    [man.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [man GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        [netWorkManager stopMonitoring];
        
        //请求成功归档储存请求的数据.
        BOOL result   = [NSKeyedArchiver archiveRootObject:responseObject toFile:textFilePath];
        
//        BOOL result = [data writeToFile:textFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
//        BOOL result = [responseObject writeToURL:[NSURL URLWithString:textFilePath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
        
        if (result) {
            NSLog(@"写入文件成功");
        }

        
        responseObj(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //请求失败(没有网),从本地文件夹获取数据
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:textFilePath];

        if (result) {
            
            NSLog(@"网络加载失败,从本地获取数据");
        }
        
        err(error);
        responseObj(result);
        
    }];
}

+ (void)POSTWithURL:(NSString *)urlStr
                par:(NSDictionary *)dic
            success:(void (^)(id))response filed:(void (^)(NSError *))err
{
    
    
    AFHTTPSessionManager *man = [AFHTTPSessionManager manager];
    
    [man.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [man POST:urlStr parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        response(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        err(error);
        
    }];
    
    
}

@end
